package com.kob.backend.controller.user.account;

import com.kob.backend.mapper.TaskMapper;
import com.kob.backend.pojo.Task;
import com.kob.backend.service.impl.utils.FileUtils;
import com.kob.backend.service.user.task.TaskService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 数据库查询任务，显示到前端
 */
@RestController
public class TaskController {

    @Autowired
    TaskService taskService;


    /**
     * 请求方式：get
     * url:/user/task/gettasklist/
     * 参数：无
     * 返回值类型map，“list”：list，list内为若干task对象
     */
    @GetMapping("/user/task/gettasklist/")
    public Map<String, Object> getTaskList() {
        Map<String, Object> map = new HashMap<>();
        List<Task> taskList = taskService.getTask();
        map.put("list", taskList);
        return map;

        // "username", "hyh"
        // "age", "18"
    }

    /**
     * 请求方式：post
     * url:/user/task/addtask/
     * 参数：taskname，taskinfo
     * 返回值类型map，"error_message"："success"
     * @return
     */
    @PostMapping("/user/task/addtask/")
    public Map<String,String> addTask(@RequestParam Map<String, String> map){
        String taskname = map.get("taskname");
        String taskinfo = map.get("taskinfo");
        return taskService.addTask(taskname,taskinfo);
    }

    /**
     * 请求方式：post
     * url:/user/task/tasktask/
     * 参数：id
     * 返回值类型map，"task"：task对象
     * @return
     */
    @GetMapping("/user/task/tasktask/")
    public Map<String, Object> takeTask(@RequestParam Map<String, String> map){
        int id =Integer.valueOf( map.get("id"));
        Map<String, Object> taskMap = new HashMap<>();
        taskMap.put("task",taskService.takeTaskById(id));
        return taskMap;
    }

    @GetMapping("/user/task/download/")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam int id) {
        Task task = taskService.selectTaskById(id);
        String taskname = task.getTaskname();
        String fileName = taskname + ".py";// 文件名
        String result = FileUtils.downloadFiles(request, response, fileName);
        if (request == null) {
            return null;
        }
        return result;
    }

}
